/**
 * Created by perqin on 16-12-6.
 */

'use strict';

/**
 * Module dependencies
 */
var mongoose = require('mongoose'),
  http = require('http'),
  config = require('../../../../config/config'),
  Story = mongoose.model('Story'),
  Photo = mongoose.model('Photo');

/**
 * Get one photo
 */
exports.get = function (req, res, next) {
  res.status(200).json(req.photo);
};

/**
 * Remove one photo
 */
exports.remove = function (req, res, next) {
  if (req.photo.owned_by._id.toString() === req.user._id.toString()) {

    // update the photos info of story
    Story.findById(req.photo.in_story._id).exec(function (err, story) {
      if (err) {
        return res.status(422).send({
          message: 'query story error'
        });
      }
      if (story) {
        // remove in story
        var photos = story.photos;
        for (var i = 0; i < photos.length; ++i) {
          if (photos[i]._id.toString() === req.photo._id.toString()) photos.splice(i, 1);
        }
        story.photos = photos;
        story.save(function (err) {
          if (err) {
            return res.status(422).send({
              message: 'delete photo from story error'
            });
          } else {
            return res.status(200).send();
          }
        });
      }
    });

    // delete the photo from database
    req.photo.remove(function (err) {
      if (err) return res.status(422).send();

      res.status(200).send();
    });
  } else {
    return res.status(401).send({
      message: 'you are not the owner of this photo'
    });
  }
};

/**
 * List all photos in a story
 */
exports.listInStory = function (req, res, next) {
  res.status(200).json(req.story.photos);
};

/**
 * Get one photo in a story
 */
exports.getInStory = function (req, res, next) {
  if (!req.photo.in_story._id.toString() === req.story._id.toString()) return res.status(404).send();

  res.status(200).json(req.photo);
};

/**
 * Remove one photo from a story
 */
exports.removeInStory = function (req, res, next) {
  if (req.photo.owned_by._id.toString() === req.user._id.toString()) {

    if (req.photo.in_story._id.toString() === req.story._id.toString()) {

      // remove in story
      var story = req.story;
      var photos = story.photos;
      for (var i = 0; i < photos.length; ++i) {
        if (photos[i]._id.toString() === req.photo._id.toString()) photos.splice(i, 1);
      }
      story.photos = photos;
      story.save(function (err) {
        if (err) {
          return res.status(422).send({
            message: 'delete photo from story error'
          });
        } else {
          return res.status(200).send();
        }
      });

      // remove from collections
      req.photo.remove(function (err) {
        if (err) return res.status(422).send();

        res.status(200).send();
      });
    } else {
      return res.status(404).send();
    }
  } else {
    return res.status(401).send({
      message: 'you are not the owner of this photo'
    });
  }
};

/**
 * Add uploaded photos
 */
exports.addUploadedPhotosToStory = function (req, res, next) {
  /*
    http.get({
    host: config.fileServer.host,
    port: config.fileServer.port,
    path: '/upload/' + req.body.upload_id
  }, function (fileRes) {
    if (fileRes.statusCode !== 200) return res.status(422).send();

    var rawResBody = '';
    fileRes.setEncoding('utf8');
    fileRes.on('data', function (chunk) {
      rawResBody += chunk;
    });
    fileRes.on('end', function () {
      try {
        var jsonFileResBody = JSON.parse(rawResBody);
        var photo = new Photo();
        photo.owned_by = req.user._id;
        photo.in_story = req.story._id;
        photo.thumbnail_size = jsonFileResBody.thumbnail_size;
        photo.thumbnail_url = jsonFileResBody.thumbnail_url;
        photo.preview_size = jsonFileResBody.preview_size;
        photo.preview_url = jsonFileResBody.preview_url;
        photo.origin_size = jsonFileResBody.origin_size;
        photo.origin_url = jsonFileResBody.origin_url;
        photo.save(function (err, savedPhoto) {
          if (err) return res.status(422).send();

          res.status(201).json(savedPhoto);
        });
      } catch (e) {
        console.error(e);
        return res.status(422).send();
      }
    });
  });
  */

  // just for test to add a assemble photo
  var photo = new Photo();
  photo.in_story = req.story._id;
  photo.owned_by = req.user._id;

  photo.save(function (err) {
    if (err) {
      return res.status(422).send({
        message: 'save photo error'
      });
    }
  });

  // add photo ref to story
  var story = req.story;
  var story_photos = story.photos;
  story_photos.push(photo);
  story.photos = story_photos;

  story.save(function (err) {
    if (err) {
      res.status(422).send({
        message: 'add photo to story error'
      });
    } else {
      res.json(photo);
    }
  });
};

/**
 * Photo middleware
 */
exports.photoById = function (req, res, next, id) {
  if (!mongoose.Types.ObjectId.isValid(id)) return res.status(400).json({
    message: 'Photo ID is invalid'
  });

  Photo.findById(id).exec(function (err, photo) {
    if (err) return next(err);

    if (!photo) return res.status(400).json({
      message: 'No photo with that ID has been found'
    });

    req.photo = photo;
    next();
  });
};
